package start.doubudouyin.controller;

import jakarta.annotation.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import start.doubudouyin.entity.DateNum;
import start.doubudouyin.entity.Videoinfo;
import start.doubudouyin.entity.join.VideoPlay;
import start.doubudouyin.service.FollowService;
import start.doubudouyin.service.IdgenerateService;
import start.doubudouyin.service.VideoinfoService;
import start.doubudouyin.service.VideolikeService;
import start.doubudouyin.utils.Idgenerate;
import start.doubudouyin.utils.Result;
import start.doubudouyin.utils.Time;
import start.doubudouyin.utils.VideoRead;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/videoinfo")
@CrossOrigin(origins = "http://localhost:5173/")
public class VideoinfoController {

    @Resource
    private VideoinfoService videoinfoService;
    @Resource
    private IdgenerateService idgenerateService;


    @PostMapping(value = "/videoupload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result videoupload(
            @RequestPart("videoFile") MultipartFile videoFile,
            @RequestParam("userId") String userId
    ) {
        try {
            // 1. 处理视频文件，获取存储信息
            VideoRead.VideoProcessResult fileResult = VideoRead.processVideoFile(videoFile);
            String storedFileName = fileResult.storedFileName();

            // 2. 使用VideoRead工具类生成前端可访问的URL
            String videoUrl = VideoRead.generateVideoUrl(storedFileName);

            // 3. 组装视频信息
            Videoinfo videoinfo = new Videoinfo();
            videoinfo.setUserId(userId);
            videoinfo.setVideoUrl(videoUrl); // 这里使用生成的URL，而不是本地磁盘路径
            videoinfo.setVideoSize(fileResult.videoSizeMB());
            videoinfo.setVideoTime(fileResult.videoTimeSeconds());

            // 4. 生成视频ID并保存
            Date date = new Date();
            if (idgenerateService.isDateExist(Time.getDate(date)) == null) {
                String videoId = Idgenerate.videoIdgenerate(1);
                videoinfo.setVideoId(videoId);
                if (videoinfoService.Videoupload(videoinfo) > 0) {
                    idgenerateService.insertDate(date);
                    idgenerateService.updateVideonum(Time.getDate(date));
                }
            } else {
                String videoId = Idgenerate.videoIdgenerate(
                        idgenerateService.getuploadnum(Time.getDate(date)) + 1
                );
                videoinfo.setVideoId(videoId);
                if (videoinfoService.Videoupload(videoinfo) > 0) {
                    idgenerateService.updateVideonum(Time.getDate(date));
                }
            }

            return Result.success("视频上传成功", videoinfo.getVideoId());
        } catch (IllegalArgumentException e) {
            return Result.error("400", e.getMessage());
        } catch (IOException e) {
            return Result.error("500", "文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            return Result.error("500", "视频上传失败: " + e.getMessage());
        }
    }

    @PutMapping("/videoinfoupload")
    public Result videoinfoupload(@RequestParam("videoId") String videoId,
            @RequestParam("title") String title,
            @RequestParam("description") String description,
            @RequestParam("videoLabel") String videoLabel){
        if(videoinfoService.Videoinfoupload(title,description,videoLabel,videoId)>0){

            return Result.success("提交成功，请等待审核",null);
        }else{
            return Result.error("300","提交失败");
        }
    }

    //获取获赞数
    @GetMapping("/getlikesCount")
    public Result getlikesCount(@RequestParam("userId") String userId) {
        Integer count = videoinfoService.GetLikesCount(userId);
        if (count == null) {
            return Result.error("300", "系统错误，请稍后再试!");
        }
        return Result.success(count);
    }

    //获取视频标签数据
    @GetMapping("/getVideoLabelsData")
    public Result getVideoLabelsData(){
        List<Integer> videoLabelData =videoinfoService.getVideoLabelsData();
        return Result.success(videoLabelData);
    }

    //获取近30天发布的视频数
    @GetMapping("/getVideoNumRange30")
    public Result getVideoNumRange30(){
        DateNum dateNum =videoinfoService.getVideoNumRange30();
        return Result.success(dateNum);
    }

    //获取所有视频信息
    @GetMapping("/findAll")
    public Result findAll(@RequestParam("videoStatus") Integer videoStatus) {
        List<VideoPlay> list = videoinfoService.FindAll(videoStatus);
        if(list==null){
            return Result.error("300","还没有视频呢");
        }else{
            return Result.success(list);
        }
    }

    /**
     * 根据id获取视频信息
     */
    @GetMapping("/getVideoInfoById")
    public Result getVideoInfoById(@RequestParam("videoId") String videoId) {
        Videoinfo videoinfo = videoinfoService.GetVideoInfoById(videoId);
        if(videoinfo==null){
            return Result.error("300","还没有视频呢");
        }else{
            return Result.success(videoinfo);
        }
    }

    /**
     * 更新视频审核状态
     */
    @PutMapping("/updateVideoStatus")
    public Result updateVideoStatus(@RequestParam("videoStatus") Integer videoStatus,@RequestParam("videoId") String videoId){
        if(videoinfoService.UpdateVideoStatus(videoStatus,videoId)>0){
            return Result.success("更新成功",null);
        }else{
            return Result.error("300","更新失败");
        }
    }

    /**
     * 删除视频
     */
    @PutMapping("/deleteVideoById")
    public Result deleteVideoById(@RequestParam("videoId") String videoId){
        if(videoinfoService.deleteVideoById(videoId)>0){
            return Result.success("删除成功",null);
        }else{
            return Result.error("300","删除失败");
        }
    }

    /**
     * 更新视频通过时间
     */
    @PutMapping("/updateVideoPassTime")
    public Result updateVideoPassTime(@RequestParam("videoId") String videoId){
        if(videoinfoService.updateVideoPassTime(videoId)>0){
            return Result.success("更新成功",null);
        }else{
            return Result.error("300","更新失败");
        }
    }

    @Resource
    private VideolikeService videolikeService;

    @Resource
    private FollowService followService;

    /**
     * 获取视频信息并添加点赞和关注状态
     */
    private List<VideoPlay> getVideoAll(Integer videoStatus, String followerId) {
        List<VideoPlay> list = videoinfoService.FindAll(videoStatus);
        for (VideoPlay videoPlay : list) {
            String videoId = videoPlay.getVideoId();
            String followedId = videoPlay.getUserId();

            Boolean isLiked = videolikeService.isLiked(followerId, videoId);
            Boolean isFollowed = followService.isFollowed(followerId, followedId);
            Boolean isFriend = followService.isFriend(followerId, followedId);

            videoPlay.setIsLiked(isLiked);
            videoPlay.setIsFollowed(isFollowed);
            videoPlay.setIsFriend(isFriend);
        }
        return list;
    }

    @GetMapping("/getVideoInfo")
    public Result getVideoInfo(@RequestParam("videoStatus") Integer videoStatus, @RequestParam("followerId") String followerId) {
        List<VideoPlay> list = getVideoAll(videoStatus, followerId);
        return Result.success(list);
    }

    /**
     * 获取用户点赞的视频
     */
    @GetMapping("/getLikeVideoInfo")
    public Result getLikeVideoInfo(@RequestParam("videoStatus") Integer videoStatus, @RequestParam("followerId") String followerId) {
        List<VideoPlay> list = getVideoAll(videoStatus, followerId);
        List<VideoPlay> likedVideos = list.stream()
                .filter(VideoPlay::getIsLiked)
                .toList();
        return Result.success(likedVideos);
    }

    /**
     * 获取用户关注的视频
     */
    @GetMapping("/getVideoFollowedInfo")
    public Result getVideoFollowedInfo(@RequestParam("videoStatus") Integer videoStatus, @RequestParam("followerId") String followerId) {
        List<VideoPlay> list = getVideoAll(videoStatus, followerId);
        List<VideoPlay> followedVideos = list.stream()
                .filter(VideoPlay::getIsFollowed)
                .toList();
        return Result.success(followedVideos);
    }

    /**
     * 获取用户朋友的视频
     */
    @GetMapping("/getVideoFriendsInfo")
    public Result getVideoFriendsInfo(@RequestParam("videoStatus") Integer videoStatus, @RequestParam("followerId") String followerId) {
        List<VideoPlay> list = getVideoAll(videoStatus, followerId);
        List<VideoPlay> followedVideos = list.stream()
                .filter(VideoPlay::getIsFriend)
                .toList();
        return Result.success(followedVideos);
    }

    /**
     * 获取用户的视频
     */
    @GetMapping("/getMyVideoInfo")
    public Result getMyVideoInfo(@RequestParam("videoStatus") Integer videoStatus,
                                 @RequestParam("followerId") String followerId) {
        List<VideoPlay> list = getVideoAll(videoStatus, followerId);

        // 过滤出 userId 等于 followerId 的视频
        List<VideoPlay> userVideos = list.stream()
                .filter(videoPlay -> followerId.equals(videoPlay.getUserId()))
                .toList();

        return Result.success(userVideos);
    }


}
